package com.example.t1.activity;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.R.integer;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;

import com.example.t1.BaseViewActivity;
import com.example.t1.R;
import com.example.t1.activity.Activity8.SocketClient.As;

/**
 * 
 * 名称：Activity8.java 描述：socket请求以及响应
 * 
 * @author 智迅 zhixun123@gmail.com
 * @date：2013-12-30 上午9:43:30
 */
@SuppressLint("NewApi")
public class Activity8 extends BaseViewActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_activity8);
	SocketClient client = new SocketClient("192.168.1.97", 60000);
	// client.sendMsg("来自android客户端");
	As as = client.As();
	as.execute(1000);
    }

    public class SocketClient {
	Socket client;

	public SocketClient(String site, int port) {
	    try {
		client = new Socket(site, port);
		System.out.println("Client is created! site:" + site + " port:"
			+ port);
	    } catch (UnknownHostException e) {
		e.printStackTrace();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}

	public As As() {
	    return new As();
	}

	public String sendMsg(String msg) {
	    try {
		BufferedReader in = new BufferedReader(new InputStreamReader(
			client.getInputStream()));
		PrintWriter out = new PrintWriter(client.getOutputStream());
		out.println(msg);
		out.flush();
		return in.readLine();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	    return "";
	}

	public String accepte() {
	    try {
		DataInputStream din = new DataInputStream(
			client.getInputStream());
		String str = "";
		do {
		    str = din.readUTF();
		    if (!"".equals(str)) {
			return str;
		    }
		} while ("".equals(str));

	    } catch (IOException e) {
		e.printStackTrace();
	    }
	    return null;

	}

	public void closeSocket() {
	    try {
		client.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}

	class As extends AsyncTask<Integer, integer, String> {

	    @Override
	    protected String doInBackground(Integer... params) {
		return accepte();
	    }

	    @SuppressLint("NewApi")
	    @Override
	    protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if (result != null) {
		    showToast(result);
		}
	    }
	}
    }

}
